package com.programmercarl.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode.cn/problems/binary-tree-paths/description/
 *
 * @author yulongtian
 * @create 2024-12-18 10:53
 */
public class Test09 {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        Test09 test09 = new Test09();
        TreeNode root = test09.new TreeNode(1);
        TreeNode node2 = test09.new TreeNode(2);
        TreeNode node3 = test09.new TreeNode(3);
        TreeNode node5 = test09.new TreeNode(5);

        root.left = node2;
        root.right = node3;
        node2.right = node5;

        test09.binaryTreePaths(root);
    }

    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        Stack<Integer> path = new Stack<>();
        preOrder(root, res, path);
        return res;
    }

    /**
     * 根左右
     *
     * @param root
     * @param res
     * @param path
     * @return
     */
    public void preOrder(TreeNode root, List<String> res, Stack<Integer> path) {
        if (root == null) {
            return;
        }
        path.add(root.val);
        if (root.left == null && root.right == null) {
            ArrayList<Integer> list = new ArrayList<>(path);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                if (i == list.size() - 1) {
                    sb.append(list.get(i));
                    continue;
                }
                sb.append(list.get(i)).append("->");
            }
            res.add(sb.toString());
        }
        preOrder(root.left, res, path);
        preOrder(root.right, res, path);
        path.pop();
    }


}
